package com.sh.test;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description: 提交线程池的实现
 */
public class MyThreadPool {

    private int num; // 计数器
    private int corePoolSize;  // 核心线程数
    private int maximumPoolSize;  // 最大线程数
    private int workSize;   // 等待队列大小
    //    private long keepAliveTime;
    //    private  TimeUnit unit;
    //    private BlockingQueue<Runnable> workQueue;
    private List<Runnable> tasks = Collections.synchronizedList(new LinkedList<Runnable>());

    public MyThreadPool(int corePoolSize, int maximumPoolSize, int workSize) {
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workSize = workSize;
    }

    public void submit(Runnable runnable) {
        if (tasks.size() >= workSize) {
            System.out.println("任务" + runnable.toString() + "已经被拒绝");
        } else {
            tasks.add(runnable);
            execTask(runnable);
        }
    }

    private void execTask(Runnable runnable) {
        if (num < corePoolSize) {
            new MyWorker("核心线程" + num, tasks).start();
            num++;
        } else if (num < maximumPoolSize) {
            new MyWorker("非核心线程" + num, tasks).start();
            num++;
        } else {
            System.out.println("任务" + runnable.toString() + "已经被存到队列中");
        }
    }


}

